import java.net.*;
import java.io.*;
import java.util.*;

/** ServerTalk3.java and LocalTalk2.java:
    One ServerTalk3.java and multiple LocalTalk2.java running instances
 can send and receive messages as objects to each other. The programs
 have the following features:

	1. The server accepts multiple client connections.
	2. ObjectInputStream and ObjectOutputStream are used to send
	   and received object.
	3. One thread is started to handle each clinet connection.
*/
   
public class ServerTalk3 {
   public static void main(String args[] ) {
      try {
        ServerSocket ssk = new ServerSocket(8900);
	int nextAgentNum = 1;
        while ( true ) {
		Socket       sk = ssk.accept();
		Agent	     agent = new Agent(nextAgentNum, sk) ;
		agent.start();
		nextAgentNum++;
        }
      } catch (Exception e) { }
   }
}

class Agent extends Thread {
   Socket sk;
   int    aNum; 
   public Agent(int aNum, Socket sk) { this.aNum = aNum; this.sk = sk; }

   public void run() {

      try {
	int mNum = 1;
	ObjectOutputStream out ;
	ObjectInputStream in;
	String message;

	out = new ObjectOutputStream(sk.getOutputStream());
	in = new ObjectInputStream(sk.getInputStream());

	while ( true ) {
		message = "Server message " + (mNum ++) + " from agent " + aNum;
		out.writeObject( message );
		out.flush();

		message = (String) in.readObject();
		System.out.println("Message received by Server: " + message);

		Thread.sleep( (int)(Math.random() * 2000) + 500);
	}
      } catch (Exception e) { e.printStackTrace(); }
   }
}

